package com.changestuffs.commons.chain;

import java.lang.annotation.Annotation;

import com.google.common.eventbus.EventBus;


public class ChainProccessor {

	private final EventBus eventBus = new EventBus();
	private ChainWrapper first;
	
	public ChainProccessor(ChainOfResponsibility ... chain){
		if(chain == null || chain.length == 0)
			throw new RuntimeException("Chain is null or its size is 0");
		ChainWrapper lastElement = null;
		for(ChainOfResponsibility element : chain){
			ChainWrapper wrapper = new ChainWrapper(eventBus, element);
			Annotation annotation = element.getClass().getAnnotation(SubscribedChain.class);
			if(annotation != null && SubscribedChain.class == annotation.annotationType()){
				System.out.println("Registering to event bus: "+element);
				eventBus.register(element);
			}
			if(first == null){
				first = wrapper;
				lastElement = first;
			}else{
				fillChain(lastElement, wrapper);
				lastElement = wrapper;
			}
		}
	}
	
	private void fillChain(ChainWrapper previusElement, ChainWrapper nextElement){
		previusElement.setNext(nextElement);
	}
	
	public void start(){
		first.execute();
	}
	
}
